package bestv.kss.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import bestv.kss.pojo.Sectconfig;

import com.datastax.driver.core.*;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.mapping.*;

@Controller
@RequestMapping("/sectconfig/")
public class SectconfigController extends CassBase {

	@RequestMapping("findall.do")
	@ResponseBody
	public List<Sectconfig> findall() {
		Statement statement = QueryBuilder.select().all()
				.from(KeyspaceName, "chain_sectconfig");
		// ResultSet results = getSession().execute(statement);
		// return getSession().execute(statement).all();
		List<Row> rows = CassSession.execute(statement).all();
		List<Sectconfig> livekeys = new ArrayList<Sectconfig>();
		for (Row row : rows) {
			Sectconfig livekey = new Sectconfig(row.getString("id"),
					row.getString("se"), row.getString("ct"),
					row.getInt("strategy"));
			livekeys.add(livekey);
		}
		return livekeys;
	}

	@RequestMapping("getone.do")
	public String getone(HttpServletRequest request, String mode, String id) {
		request.setAttribute("savemode", mode);
		if (mode.equals("save")) {
			Sectconfig sect = findone(id);
			request.setAttribute("sectPage", sect);
		}
		return "sectconfig";
	}

	public Sectconfig findone(String id) {
		Mapper<Sectconfig> mapper = new MappingManager(CassSession)
				.mapper(Sectconfig.class);
		return mapper.get(id);
	}

	@RequestMapping("save.do")
	@ResponseBody
	public String save(HttpServletRequest request, String savemode,
			Sectconfig sectPage) {
		Mapper<Sectconfig> mapper = new MappingManager(CassSession)
				.mapper(Sectconfig.class);
		String oldid = sectPage.getId();
		String id = sectPage.getSe() + "_" + sectPage.getCt();
		sectPage.setId(id);
		if (savemode.equals("save")) {
			delete(oldid);
		}
		mapper.save(sectPage);
		return "succ";
	}

	@RequestMapping("del.do")
	@ResponseBody
	public String deleteChecked(HttpServletRequest request, final String[] ids) {
		for (String delid : ids) {
			delete(delid);
		}
		return "succ";
	}

	public void delete(String id) {
		Mapper<Sectconfig> mapper = new MappingManager(CassSession)
				.mapper(Sectconfig.class);
		Sectconfig pojo = new Sectconfig();
		pojo.setId(id);
		mapper.delete(pojo);
	}

}
